package org.zergle.scrapture.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PropertiesManager {
	private static Properties properties = new Properties();
	private static final String RESOURCES = "/org/zergle/scrapture/gui/resources/resources.properties";
	private static final Pattern PATTERN_PARAM = Pattern.compile("\\$\\{.+?\\}");
	
	private PropertiesManager() {}
	
	static {
		try {
			InputStream is = PropertiesManager.class.getResourceAsStream(RESOURCES);
			properties.load(is);
			for (Iterator<Object> propIt = properties.keySet().iterator(); propIt.hasNext();) {
				String key = (String) propIt.next();
				String value = properties.getProperty(key);
				Matcher matcher = null;
				while ((matcher = PATTERN_PARAM.matcher(value)).find()) {
					String refKey = value.substring(matcher.start(), matcher.end());
					String refVal = PropertiesManager.get(refKey.substring(2, refKey.length() - 1));
					value = value.replaceAll(PATTERN_PARAM.pattern(), refVal);
					properties.setProperty(key, value);
				}
			}
		} catch (IOException e) {
			e.printStackTrace(System.err);
			System.exit(0);
		}
	}
	
	public static String get(String key) {
		return properties.getProperty(key);
	}
	
	public static String get(Object key) {
		return properties.getProperty(String.valueOf(key));
	}
}
